﻿using System.Xml;

namespace RunCamlSample.QueryBuilders
{
    /// <summary>
    /// Create By: Nguyen Thanh Tung
    /// </summary>
    public class QueryBuilder : BaseQueryBuilder
    {
        readonly XmlDocument document = new XmlDocument();
        private readonly XmlNode query;
        private bool isAnd;
        private XmlNode whereNode;
        private XmlNode whereParentNode;
        private XmlNode orderByNode;

        public QueryBuilder()
        {
            query = AddXmlElement(document, "Query", "");
        }

        public QueryBuilder Load(string xml)
        {
            document.LoadXml(xml);

            return this;
        }

        public QueryBuilder Where(string field, QueryOperation operation, string value, string valueType)
        {
            if (whereNode == null)
            {
                whereNode = AddXmlElement(query, "Where", "");    
            }

            if (isAnd)
            {
                if (whereParentNode == null)
                    whereParentNode = AddXmlElement(whereNode, "And", "");
            }
            else
            {
                whereParentNode = whereNode;
            }

            XmlNode conditionNode = AddXmlElement(whereParentNode, operation.ToString(), "");

            XmlNode fieldNode = AddXmlElement(conditionNode, "FieldRef", "");

            AddXmlAttribute(fieldNode, "Name", field);

            XmlNode valueNode = AddXmlElement(conditionNode, "Value", value);

            AddXmlAttribute(valueNode, "Type", valueType);

            return this;
        }

        public QueryBuilder OrderBy(string fieldName, bool isAscending)
        {
            if (orderByNode == null)
            {
                orderByNode = AddXmlElement(query, "OrderBy", "");
            }

            XmlNode orderClause = AddXmlElement(orderByNode, "FieldRef", "");

            AddXmlAttribute(orderClause, "Name", fieldName);
            AddXmlAttribute(orderClause, "Ascending", isAscending.ToString());

            return this;
        }

        public QueryBuilder And()
        {
            if (!isAnd)
            {
                isAnd = true;
            }

            return this;
        }

        public QueryBuilder EndAnd()
        {
            isAnd = false;
            return this;
        }

        public XmlNode ToXmlNode()
        {
            return query;
        }
    }
}